package com.oocl.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.exception.MyException;
import com.oocl.pojo.Food;
import com.oocl.pojo.Muser;
import com.oocl.service.FoodService;
import com.oocl.service.MuserService;
import com.oocl.service.impl.FoodServiceImpl;
import com.oocl.service.impl.MuserServiceImpl;
import com.oocl.util.PropertiesFactory;
import com.oocl.util.RequestUtil;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		// check
		boolean isError = false;
		if (name == null || "".equals(name)) {
			request.setAttribute("nameMsg", "name can not be emtry");
			isError = true;
		}
		if (password == null || "".equals(password)) {
			request.setAttribute("pwdMsg", "password can not be emtry");
			isError = true;
		}

		if (isError) {
			request.getRequestDispatcher("login.jsp")
					.forward(request, response);
			return;
		}
		// login
		Muser m = new Muser();
		m.setMname(name);
		m.setPwd(password);
		MuserService mSer = new MuserServiceImpl();

		Muser muser = null;
		try {
			muser = mSer.loadMuser(m);

			if (muser != null) {
				if ("2".equals(muser.getStatus2())) {
					request.getSession().setAttribute("name", muser.getMname());
					request.getSession().setAttribute("mid", muser.getMid());
					List<Food> list = getFoods( muser.getMid());
					request.getSession().setAttribute("list", list);
					request.getRequestDispatcher("sec/list").forward(request,
							response);
				} else {
					// 对接AS
					String uri = "?icnum="+muser.getIcnum();
					//RequestUtil.request(uri, type, params, clazz)
					
				}

			} else {
				request.getRequestDispatcher("login.jsp").forward(request,
						response);
			}

		} catch (MyException e) {
			response.sendRedirect("exception.jsp");
		}
}

	
	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doGet(request,response);
		
	}
	
	private List<Food> getFoods(String mid) throws MyException {
        FoodService fSer = new FoodServiceImpl();
        List<Food> list = fSer.loadFoodsByIcnum(mid);
		return list;
	}


	
}
